<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Models\Freelancer;
use App\Models\Tenant;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use Log;
class FreelancerAuthController extends Controller
{
    /**
     * 自由职业者注册
     */
    public function register(Request $request)
    {
        Log::info('Freelancer register request', $request->all());
        $validator = Validator::make($request->all(), [
            'tenant_id' => 'required|exists:tenants,id',
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255',
            'phone' => 'required|string|max:20',
            'password' => 'required|string|min:8|confirmed',
            'id_card' => 'required|string|size:18',
            'real_name' => 'required|string|max:255',
            'gender' => 'required|in:male,female',
            'birth_date' => 'required|date',
            'address' => 'required|string|max:500',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => '验证失败',
                'errors' => $validator->errors()
            ], 422);
        }

        // 检查租户状态
        $tenant = Tenant::find($request->tenant_id);
        if (!$tenant || $tenant->status !== 'active') {
            return response()->json([
                'success' => false,
                'message' => '租户不存在或已停用'
            ], 400);
        }

        // 检查邮箱和手机号是否已存在
        $existingFreelancer = Freelancer::where('tenant_id', $request->tenant_id)
            ->where(function ($query) use ($request) {
                $query->where('email', $request->email)
                      ->orWhere('phone', $request->phone)
                      ->orWhere('id_card', $request->id_card);
            })
            ->first();

        if ($existingFreelancer) {
            return response()->json([
                'success' => false,
                'message' => '邮箱、手机号或身份证号已被注册'
            ], 400);
        }

        try {
            $freelancer = Freelancer::create([
                'tenant_id' => $request->tenant_id,
                'name' => $request->name,
                'email' => $request->email,
                'phone' => $request->phone,
                'password' => Hash::make($request->password),
                'id_card' => $request->id_card,
                'real_name' => $request->real_name,
                'gender' => $request->gender,
                'birth_date' => $request->birth_date,
                'address' => $request->address,
                'status' => 'pending_verification',
                'verification_status' => Freelancer::VERIFICATION_PENDING,
                'id_card_recognition_status' => Freelancer::RECOGNITION_PENDING,
                'face_recognition_status' => Freelancer::RECOGNITION_PENDING,
            ]);

            return response()->json([
                'success' => true,
                'message' => '注册成功，请等待审核',
                'data' => [
                    'freelancer' => $freelancer->makeHidden(['password'])
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '注册失败，请稍后重试'
            ], 500);
        }
    }

    /**
     * 自由职业者登录
     */
    public function login(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'tenant_id' => 'required|exists:tenants,id',
            'login' => 'required|string', // 可以是邮箱或手机号
            'password' => 'required|string',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => '验证失败',
                'errors' => $validator->errors()
            ], 422);
        }

        // 检查租户状态
        $tenant = Tenant::find($request->tenant_id);
        if (!$tenant || $tenant->status !== 'active') {
            return response()->json([
                'success' => false,
                'message' => '租户不存在或已停用'
            ], 400);
        }

        // 查找自由职业者
        $freelancer = Freelancer::where('tenant_id', $request->tenant_id)
            ->where(function ($query) use ($request) {
                $query->where('email', $request->login)
                      ->orWhere('phone', $request->login);
            })
            ->first();

        if (!$freelancer || !Hash::check($request->password, $freelancer->password)) {
            return response()->json([
                'success' => false,
                'message' => '登录凭据不正确'
            ], 401);
        }

        // 检查自由职业者状态
        if ($freelancer->status === 'suspended') {
            return response()->json([
                'success' => false,
                'message' => '账号已被暂停，请联系管理员'
            ], 403);
        }

        if ($freelancer->status === 'rejected') {
            return response()->json([
                'success' => false,
                'message' => '账号审核未通过，请重新提交资料'
            ], 403);
        }

        try {
            // 创建访问令牌
            $token = $freelancer->createToken('freelancer-token')->plainTextToken;

            // 更新最后登录时间
            $freelancer->update([
                'last_login_at' => now(),
                'last_login_ip' => $request->ip()
            ]);

            return response()->json([
                'success' => true,
                'message' => '登录成功',
                'data' => [
                    'freelancer' => $freelancer->makeHidden(['password']),
                    'token' => $token
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '登录失败，请稍后重试'
            ], 500);
        }
    }

    /**
     * 获取当前自由职业者信息
     */
    public function me(Request $request)
    {
        $freelancer = $request->user();
        
        return response()->json([
            'success' => true,
            'data' => [
                'freelancer' => $freelancer->makeHidden(['password'])
            ]
        ]);
    }

    /**
     * 修改密码
     */
    public function changePassword(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'current_password' => 'required|string',
            'password' => 'required|string|min:8|confirmed',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => '验证失败',
                'errors' => $validator->errors()
            ], 422);
        }

        $freelancer = $request->user();

        if (!Hash::check($request->current_password, $freelancer->password)) {
            return response()->json([
                'success' => false,
                'message' => '当前密码不正确'
            ], 400);
        }

        try {
            $freelancer->update([
                'password' => Hash::make($request->password)
            ]);

            return response()->json([
                'success' => true,
                'message' => '密码修改成功'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '密码修改失败，请稍后重试'
            ], 500);
        }
    }

    /**
     * 退出登录
     */
    public function logout(Request $request)
    {
        try {
            $request->user()->currentAccessToken()->delete();

            return response()->json([
                'success' => true,
                'message' => '退出登录成功'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '退出登录失败'
            ], 500);
        }
    }

    /**
     * 退出所有设备
     */
    public function logoutAll(Request $request)
    {
        try {
            $request->user()->tokens()->delete();

            return response()->json([
                'success' => true,
                'message' => '已退出所有设备'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '操作失败'
            ], 500);
        }
    }

    /**
     * 刷新令牌
     */
    public function refreshToken(Request $request)
    {
        try {
            $freelancer = $request->user();
            
            // 删除当前令牌
            $request->user()->currentAccessToken()->delete();
            
            // 创建新令牌
            $token = $freelancer->createToken('freelancer-token')->plainTextToken;

            return response()->json([
                'success' => true,
                'message' => '令牌刷新成功',
                'data' => [
                    'token' => $token
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '令牌刷新失败'
            ], 500);
        }
    }
}
